package com.ggs.controller;

import com.ggs.utils.AliOSSUtils;
import com.ggs.vo.ResultVO;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@CrossOrigin
@RestController
public class FileController {
    @Value("${file.uploadDir}")
    private String uploadDir;
//    @PostMapping(value = "/upload",consumes = "multipart/form-data")
//    public ResultVO uploadFile(@NotNull MultipartFile file){
//        String originalFilename = file.getOriginalFilename();
//        String pathname = uploadDir + UUID.randomUUID() + "_" + originalFilename;
//
//        File targetDir = new File(uploadDir);
//        if (!targetDir.exists())
//            targetDir.mkdirs();
//        File dest = new File(pathname);
//        try {
//            file.transferTo(dest);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return ResultVO.success();
//    }
    @PostMapping(value = "/upload",consumes = "multipart/form-data")
    public ResultVO uploadFile(@RequestParam("file") @NotNull MultipartFile multipartFile){
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID() + "_" + originalFilename;
        String url = "";
        try {
            InputStream inputStream = multipartFile.getInputStream();
            url = AliOSSUtils.uploadFile(fileName, inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return ResultVO.success(url);
    }
}
